part of 'card.dart';

class _TranslationSelectionCardWloc
    extends StatefulWloc<_TranslationSelectionCardWlocState, TranslationSelectionCard>
    with TickerProviderStateMixin, CardWlocMixin {
  late final bloc.TranslationSelectionCardBloc _bloc;

  late final Map<String, AnimationController> shakeAnimationControllers;
  late final AnimationController correctAnswerColorAnimationController;

  @override
  _TranslationSelectionCardWlocState get initialState {
    return _TranslationSelectionCardWlocState(
      lexicalItem: widget.lexicalItem,
      answerOptionLexicalItems: widget.answerOptionLexicalItems,
      dialect: widget.dialect,
      safeToPronounce: widget.safeToPronounce,
      finished: false,
    );
  }

  void onLexicalItemPronunciationButtonPressed() {
    _bloc.requestLexicalItemPronunciation();
  }

  void onPronunciationCautionButtonPressed() {
    showPronunciationCautionDialog(
      context: context,
    );
  }

  void onCorrectAnswerButtonPressed() {
    final updatedState = state.copyWith(
      finished: () => true,
    );

    emit(updatedState);

    for (final shakeAnimationController in shakeAnimationControllers.values) {
      shakeAnimationController.reset();
    }

    correctAnswerColorAnimationController.forward().whenComplete(widget.onSucceeded);
  }

  void onWrongAnswerButtonPressed({
    required String lexicalItemId,
  }) {
    shakeAnimationControllers[lexicalItemId]!.forward(from: 0.0);
  }

  @override
  void initState() {
    super.initState();

    _bloc = bloc.TranslationSelectionCardBloc(
      lexicalItem: widget.lexicalItem,
      pronounceLexicalItem: translation_selection_card_di.sl(),
    );

    shakeAnimationControllers = {};

    for (final lexicalItem in state.answerOptionLexicalItems) {
      if (lexicalItem.id != state.lexicalItem.id) {
        shakeAnimationControllers[lexicalItem.id] = AnimationController(
          duration: kShakeAnimationDuration,
          vsync: this,
        );
      }
    }

    correctAnswerColorAnimationController = AnimationController(
      duration: kCardCorrectAnswerColorAnimationDuration,
      vsync: this,
    );
  }

  @override
  void didUpdateWidget(TranslationSelectionCard oldWidget) {
    super.didUpdateWidget(oldWidget);

    final updatedState = state.copyWith(
      dialect: () => widget.dialect,
      safeToPronounce: () => widget.safeToPronounce,
    );

    emit(updatedState);
  }

  @override
  void dispose() {
    _bloc.close();

    for (final shakeAnimationController in shakeAnimationControllers.values) {
      shakeAnimationController.dispose();
    }

    correctAnswerColorAnimationController.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _TranslationSelectionCardView(
      wloc: this,
    );
  }
}
